const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// ... 已有配置保持不变 ...
module.exports = {
    cache: {
        type: 'filesystem',
        buildDependencies: {
            config: [__filename]
        }
    },
    entry: './src/index.tsx',
    output: {
        filename: 'static/js/[name].[contenthash].js',
        path: path.resolve(__dirname, '../dist'),
        publicPath: '/',
        chunkFilename: 'static/js/[name].[contenthash].chunk.js'
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js', '.scss', '.sass', '.less', '.json'], // 添加 TypeScript 扩展
        alias: {
            "@": path.resolve(__dirname, "../src/"),
            components: path.resolve(__dirname, 'src/components/')
        }
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx|ts|tsx)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'thread-loader', // 新增线程池
                        options: {
                            workers: require('os').cpus().length - 1, // 自动获取核心数
                            poolTimeout: 2000 // 2秒无任务自动终止
                        }
                    },
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: [
                                ['@babel/preset-env', { modules: false }], // 关键配置
                                '@babel/preset-react',
                                '@babel/preset-typescript' // 新增 TypeScript 支持
                            ]
                        }
                    }
                ]
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.s[ac]ss$/i,
                use: [
                    // MiniCssExtractPlugin.loader,
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                config: path.resolve(__dirname, '../postcss.config.js')
                            }
                        }
                    },
                    'sass-loader'
                ]
            },
            {
                test: /\.less$/i,
                use: [
                    'style-loader',
                    'css-loader',
                    'less-loader' // 新增 less 支持
                ]
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
                generator: {
                    filename: 'static/img/[name].[hash][ext]' // 修改图片路径
                }
            }

        ]
    },
    optimization: {
        usedExports: true, // 标记未使用代码
        minimize: true,    // 开启代码压缩（已配置 TerserPlugin）
        minimizer: [
            new TerserPlugin({ // 需要先安装 terser-webpack-plugin
                parallel: true // 启用多线程压缩
            })
        ],
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'initial',
                },
                common: {
                    minChunks: 2,
                    name: 'common',
                    chunks: 'async',
                    reuseExistingChunk: true
                }
            }
        },
        runtimeChunk: {
            name: 'runtime'
        }
    },
    plugins: [
        // 在 plugins 数组中添加：
        // new HtmlWebpackPlugin({
        //     template: './public/index.html',
        //     title: process.env.APP_TITLE || '默认标题' // 读取环境变量
        // }),
        // new webpack.DefinePlugin({
        //     'process.env.APP_TITLE': JSON.stringify(process.env.APP_TITLE)
        // }),
        // new BundleAnalyzerPlugin({ analyzerMode: 'static' })
    ],
    devServer: {
        static: {
            directory: path.join(__dirname, 'dist'),
        },
        port: 3000,
        open: true,
        hot: true
    }
};
